package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.dto.CheckInApplyDto;
import com.zzyl.nursing.domain.dto.CheckInConfigDto;
import com.zzyl.nursing.domain.dto.CheckInContractDto;
import com.zzyl.nursing.domain.dto.CheckInElderDto;
import com.zzyl.nursing.domain.pojo.*;
import com.zzyl.nursing.domain.vo.TreeVo;
import com.zzyl.nursing.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-09-27
 */
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {

    private final CheckInMapper checkInMapper;
    private final ElderMapper elderMapper;
    private final BedMapper bedMapper;
    private final CheckInConfigMapper checkInConfigMapper;
    private final ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //获取老人dto
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        //获取床位配置dto
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        //获取床位dto
        Long bedId = checkInConfigDto.getBedId();
        //验证老人是否入住，如果已入住，提示老人已入住
        Elder enableElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotNull(enableElder)) {
            throw new BaseException("老人已入住，无需申请");
        }
        //如果未入住，则分配新的床位

        bedMapper.updateById(Bed.builder().id(bedId).bedStatus(1).build());

        //老人：新增或者更新
        Elder disableElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1));

        //将老人dto中数据注入到实体类
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        Elder elder = BeanUtil.toBean(elderDto, Elder.class);
        //设置剩余属性
        elder.setBedId(bedId);
        Bed bed = bedMapper.selectBedById(bedId);
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        //如果老人之前入住过就更新床位，如果没入住过就新增床位
        //禁用数据存在：说明老人之前入住过
        if (ObjectUtil.isNotNull(disableElder)) {
            //需要更新老人和床位
            elder.setId(disableElder.getId());
            elderMapper.updateById(elder);
        }
        //禁用数据不存在：说明老人之前未入住过
        else {
            //需要新增老人和床位
            elderMapper.insert(elder);

        }
        //2.3-合同：新增
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(checkInConfigDto.getStartDate().isBefore(LocalDateTime.now()) ? 1 : 0);

        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);

        //2.4-入住和入住配置：新增
        //入住
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        //入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }


}
